﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Icst.Leaflike.Web;

using System.Web.UI.HtmlControls;
using Icst.Leaflike.Data;
using Icst.Leaflike.Logging;
using Icst.Leaflike.SAFG;
using System.IO;

namespace Icst.Leaflike.Web.search
{
    public partial class search : pagesearch
    {
        protected IEnumerable<tree_searchResult> _results = new List<tree_searchResult>();
        protected override string OnSave(bool empty)
        {
            return string.Empty;
        }
        protected override void OnLoad()
        {
            bool dosearch = !string.IsNullOrEmpty(Request["s"]);
            searchResultPanel.Visible = dosearch;
            tipsPanel.Visible = !dosearch;
            if (!dosearch)
            {
                tipsTextBox.InnerHtml = SearchQuery.ToListString();
            }
            else
            {
                int page = this.ParaInt("page", 1);

                Logger.Debug("BEGIN SEARCH");
                Logger.Debug(SearchQuery.ToString());

                string Shuxing = SearchQuery[SearchOption.Shuxing];
                string Yexu = SearchQuery[SearchOption.Yexu];
                string Yexing = SearchQuery[SearchOption.Yexing];
                string Yeyuan = SearchQuery[SearchOption.Yeyuan];
                string Yejian = SearchQuery[SearchOption.Yejian];
                string Yeji = SearchQuery[SearchOption.Yeji];
                string Huaxing = SearchQuery[SearchOption.Huaxing];
                string Guoshi = SearchQuery[SearchOption.Guoshi];
                string Shupi = SearchQuery[SearchOption.Shupi];
                string Danfuye = SearchQuery[SearchOption.Danfuye];
                string Guoshiyanse = SearchQuery[SearchOption.Guoshiyanse];
                string Huaqi = SearchQuery[SearchOption.Huaqi];
                string Shugao = SearchQuery[SearchOption.Shugao];
                string Shuganyanse = SearchQuery[SearchOption.Shuganyanse];

                Func<tree_searchResult, bool> filter = p => true;
                Plant[] plants = null;
                if (SearchQuery.IsUpload)
                {
                    using(SAFGClient client = new SAFGClient())
                    {
                        Contour contour = ReadContour();
                        plants = client.SearchPlants(contour, 40);
                        if (plants == null)
                            plants = new Plant[] { };
                        long[] plantids = plants.Select(p => long.Parse(p.ID)).ToArray();
                        filter = p => plants != null && plantids.Contains(p.tree_no);

                        Yexing = string.Empty;

                        Logger.Info(plants.Length + " plants searched by SAFG.");
                    }
                }

                int total = 0;
                _results = Tree.Instance.Search(Shuxing, Yexu, Yexing, Yeyuan, Yejian, Yeji, Huaxing,
                Guoshi, Shupi, Danfuye, Guoshiyanse, Huaqi, Shugao, Shuganyanse, page, 10, filter, out total);
                    
                paginator.RecordCount = total;
                resultPanel.Visible = total > 0;
                emptyPanel.Visible = total == 0;
            }
        }
        protected Contour ReadContour()
        {
            Dictionary<string, Contour> contours = Session["contours"] as Dictionary<string, Contour>;
            if(contours != null && contours.ContainsKey(SearchQuery[SearchOption.Yexing]))
                return contours[SearchQuery[SearchOption.Yexing]];

            return new Contour() { Points = new ContourPoint[]{} };
            //string basepath = Server.MapPath("~/contours");
            //string contourFile = Path.Combine(basepath, SearchQuery[SearchOption.Yexing] + ".cont");
            //List<ContourPoint> points = new List<ContourPoint>();

            //if (File.Exists(contourFile))
            //{
            //    try
            //    {
            //        using (Stream s = new FileStream(contourFile, FileMode.Open, FileAccess.Read))
            //        using (StreamReader reader = new StreamReader(s))
            //        {
            //            //string line = reader.ReadLine();//ignore line 1
            //            //line = reader.ReadLine();//ignore line 2
            //            string line = reader.ReadLine();
            //            while (!string.IsNullOrEmpty(line))
            //            {
            //                string[] splits = line.Split(',');
            //                if (splits.Length > 1)
            //                {
            //                    int x = int.Parse(splits[0]);
            //                    int y = int.Parse(splits[1]);
            //                    points.Add(new ContourPoint(x, y));
            //                }
            //                line = reader.ReadLine();
            //            }
            //        }
            //    }
            //    catch (Exception e)
            //    {
            //        Logger.Error("FAILED TO READ CONT FROM " + contourFile + ". " + e.Message);
            //    }
            //}
            //return new Contour() { Points = points.ToArray() };
        }
    }
}
